package cgl.narada.service.p2pRelayServer;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketAddress;
import java.net.SocketException;
import java.net.UnknownHostException;

import org.apache.log4j.Logger;

/**
 * 
 * Created on Jun 2, 2006
 * 
 * @author Harshawardhan Gadgil (hgadgil@grids.ucs.indiana.edu)
 */

public class UDPConnector extends Thread {

   static Logger log = Logger.getLogger("UDPConnector");

   private DatagramSocket dsock;

   private DataProcessor processor;

   public UDPConnector(DataProcessor proc, int port) {

      processor = proc;
      try {

         InetAddress addr = null;
         try {
            addr = InetAddress.getLocalHost(); // getByName(InterfaceTester.GetAddress());
         } catch (UnknownHostException e) {
            log.error("", e);
         }

         dsock = new DatagramSocket(port, addr);
      } catch (SocketException e) {
         log.error("", e);
      }
      log.info("Accepting DATAGRAM connections: "
               + dsock.getLocalSocketAddress());
   }

   /**
    * @return Returns the socket address
    */
   public synchronized final SocketAddress getLocalAddress() {
      return dsock.getLocalSocketAddress();
   }

   public void run() {

      byte[] buf = new byte[1500];
      DatagramPacket p = new DatagramPacket(buf, buf.length);
      while (true) {
         try {
            dsock.receive(p);
            processor.processData(p.getSocketAddress(), p.getData());
         } catch (Exception e) {
            log.error("ERROR: ", e);
         }
      }
   }

   public void send(SocketAddress dest, byte[] msg) throws Exception {
      DatagramPacket p = new DatagramPacket(msg, msg.length, dest);
      // log.debug("Sending " + msg.length + " bytes to {" + dest + "}");
      dsock.send(p);
   }

   /**
    * 
    */
   public void close() throws Exception {
      dsock.close();
   }

}
